//
//  AYUserAccountViewModel.swift
//  iOSSinaWeb
//
//  Created by yws on 16/5/14.
//  Copyright © 2016年 yws. All rights reserved.
//

import UIKit

class AYUserAccountViewModel: NSObject {

    static let sharedInstance: AYUserAccountViewModel = AYUserAccountViewModel()
    
    //归档路径
    var userAcountPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last! + "/account.plist"
    
    //账号 拿到全局都能访问
    var userAccount: AYUserAccount?
    
    var isUserLogin: Bool {
        get {
           return userAccount != nil
        }
    }
    
    
    
    override init() {
        super.init()
        userAccount = loadUserAccount()
//        AMPrint(items: "\(userAccount)")
    }
    
    func loadAccessToken(code: String, callback: (error: NSError?) -> ()) {
        let urlString = "oauth2/access_token"
        
        let parameters = [
            "client_id" : client_id,
            "client_secret" : client_secret,
            "grant_type" : "authorization_code",
            "code" : code,
            "redirect_uri": redirect_uri
        ]
        
        AYAFNetworkTool.sharedInstance.request(requestMethod.POST, URLString: urlString, parameters: parameters, success: { (task, responseObject) -> Void in
            AMPrint(items: "获取AccessToken成功: \(responseObject)")
            
            //字典转模型
            
            if let result = responseObject as? [String : AnyObject] {
                let userAccount = AYUserAccount(dict: result)
                
//                AMPrint(items: "\(userAccount)")
                
                
//                AMPrint(items: "\(self.userAcountPath)")
               
                //将账号直接赋值给属性
                self.userAccount = userAccount
                
                
                //归档将模型保存到沙盒里面去
                self.saveUserAccount()
                callback(error: nil)
                
            } else {
                AMPrint(items: "转失败了")
            }
            }, failure: { (task, error) -> Void in
                AMPrint(items: "失败了: \(error)")
                callback(error: error)
        })
    }
    
    ///保存账号到沙盒里面
    func saveUserAccount() -> Void {
        if let account = userAccount {
            NSKeyedArchiver.archiveRootObject(account, toFile: self.userAcountPath)
        }
    }
    
    ///解档账号
    func loadUserAccount() -> AYUserAccount? {
        
        if let userAccount = NSKeyedUnarchiver.unarchiveObjectWithFile(userAcountPath) as? AYUserAccount{
            if userAccount.expiresDate?.compare(NSDate()) != NSComparisonResult.OrderedAscending  {
                AMPrint(items: "没有过期")
                return userAccount
            } else {
                return nil
            }
            
        } else {
            return nil
        }
    }
    
    
    
    
    // MARK: - 获取用户名称和头像
    
    func loadUserInfo(loadUserInfoCallback: () -> ()) {
        print("进来了")
        guard let access_token = userAccount?.access_token else {
            AMPrint(items: "access_token没有值")
            return
        }
        
        guard let uid = userAccount?.uid else {
            AMPrint(items: "uid没有值")
            return
        }
        
        let urlString = "2/users/show.json"
        
        let parameters = [
            "access_token": access_token,
            "uid": uid
        ]
        
        AYAFNetworkTool.sharedInstance.request(requestMethod.GET, URLString: urlString, parameters: parameters, success: { (_, responseObject) -> Void in
            if let result = responseObject as? [String: AnyObject] {
                
                let screen_name = result["screen_name"] as? String
                let avatar_large = result["avatar_large"] as? String
                
                self.userAccount?.screen_name = screen_name
                self.userAccount?.avatar_large = avatar_large
                
                AMPrint(items: "获取用户\(responseObject)")
                self.saveUserAccount()
                loadUserInfoCallback()
            }
            }) { (_, error) in
                AMPrint(items: "获取用户信息失败了\(error)")
//                print("\(error)")
        }
        
        

        
    }
    
    
    
    
    
}








